package com.jie.langlangmall.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.jie.langlangmall.common.exception.ApiException;
import com.jie.langlangmall.model.OmsCartItem;
import com.jie.langlangmall.model.PmsProductFullReduction;
import com.jie.langlangmall.model.PmsProductLadder;
import com.jie.langlangmall.model.PmsSkuStock;
import com.jie.langlangmall.portal.dao.ProductDao;
import com.jie.langlangmall.portal.domain.CartPromotionItem;
import com.jie.langlangmall.portal.domain.PromotionProduct;
import com.jie.langlangmall.portal.service.OmsPromotionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author Jie
 * @Date 2024/10/11
 * @Email 3217998214@qq.com
 * @Description 促销内容
 */
@Service
public class OmsPromotionServiceImpl implements OmsPromotionService {

    @Autowired
    private ProductDao productDao;

    @Override
    public List<CartPromotionItem> calcCartPromotion(List<OmsCartItem> cartItemList) {
        // 1. 先根据productId对CartItem进行分组，以spu为单位进行计算优惠
        Map<Long, List<OmsCartItem>> productCartMap = groupCartItemBySpu(cartItemList);
        // 2. 查询所有商品的优惠信息
        List<PromotionProduct> promotionProductList = getPromotionProductList(cartItemList);
        // 3. 根据商品促销类型计算商品促销优惠价格
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        for (Map.Entry<Long, List<OmsCartItem>> entry : productCartMap.entrySet()) {
            Long productId = entry.getKey();
            // 获取该商品的促销信息
            PromotionProduct promotionProduct = getPromotionProductById(productId, promotionProductList);
            if (promotionProduct == null) {
                throw new ApiException("没有该类商品");
            }
            List<OmsCartItem> itemList = entry.getValue();
            Integer promotionType = promotionProduct.getPromotionType();
            if (promotionType == 1) {
                // 单品促销
                for (OmsCartItem item : itemList) {
                    CartPromotionItem cartPromotionItem = new CartPromotionItem();
                    BeanUtil.copyProperties(item, cartPromotionItem);
                    cartPromotionItem.setPromotionMessage("单品促销");
                    // 商品原价=促销价
                    PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
                    if (skuStock == null) {
                        throw new ApiException("商品原价为空");
                    }
                    BigDecimal originalPrice = skuStock.getPrice();
                    // 单品促销用原价
                    cartPromotionItem.setPrice(originalPrice);
                    if (skuStock.getPromotionPrice() == null) {
                        throw new ApiException("商品[" + item.getProductName() + "]没有促销信息");
                    }
                    cartPromotionItem.setReduceAmount(originalPrice.subtract(skuStock.getPromotionPrice()));
                    cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
                    cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                    cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
                    cartPromotionItemList.add(cartPromotionItem);
                }
            } else if (promotionType == 2) {
                // TODO: 使用会员价
                handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
            } else if (promotionType == 3) {
                // 打折优惠
                int count = getCartItemCount(itemList);
                // 阶梯价格
                PmsProductLadder ladder = getProductLadder(count, promotionProduct.getProductLadderList());
                if (ladder != null) {
                    for (OmsCartItem item : itemList) {
                        CartPromotionItem cartPromotionItem = new CartPromotionItem();
                        BeanUtils.copyProperties(item, cartPromotionItem);
                        String message = getLadderPromotionMessage(ladder);
                        cartPromotionItem.setPromotionMessage(message);
                        // 商品原价=折扣*商品原价
                        PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
                        if (skuStock == null) {
                            throw new ApiException("商品原价为空");
                        }
                        BigDecimal originalPrice = skuStock.getPrice();
                        BigDecimal reduceAmount = originalPrice.subtract(ladder.getDiscount().multiply(originalPrice));
                        cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
                        cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                        cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
                        cartPromotionItemList.add(cartPromotionItem);
                    }
                } else {
                    handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
                }
            } else if (promotionType == 4) {
                // 满减
                BigDecimal totalAmount = getCartItemAmount(itemList, promotionProductList);
                PmsProductFullReduction fullReduction = getProductFullReduction(totalAmount, promotionProduct.getProductFullReductionList());
                if (fullReduction != null) {
                    for (OmsCartItem item : itemList) {
                        CartPromotionItem cartPromotionItem = new CartPromotionItem();
                        BeanUtils.copyProperties(item, cartPromotionItem);
                        String message = getFullReductionPromotionMessage(fullReduction);
                        cartPromotionItem.setPromotionMessage(message);
                        //(商品原价/总价)*满减金额
                        PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
                        if (skuStock == null) {
                            throw new ApiException("商品原价为空");
                        }
                        BigDecimal originalPrice = skuStock.getPrice();
                        BigDecimal reduceAmount = originalPrice.divide(totalAmount, RoundingMode.HALF_EVEN).multiply(fullReduction.getReducePrice());
                        cartPromotionItem.setReduceAmount(reduceAmount);
                        cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
                        cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                        cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
                        cartPromotionItemList.add(cartPromotionItem);
                    }
                } else {
                    handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
                }
            } else {
                // 无优惠
                handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
            }
        }
        return cartPromotionItemList;
    }

    /**
     * 设置满减信息
     *
     * @param fullReduction
     * @return
     */
    private String getFullReductionPromotionMessage(PmsProductFullReduction fullReduction) {
        return "满减优惠：" +
                "满" +
                fullReduction.getFullPrice() +
                "元，" +
                "减" +
                fullReduction.getReducePrice() +
                "元";
    }

    /**
     * 获取购物车中指定商品的总价
     *
     * @param itemList
     * @param promotionProductList
     * @return
     */
    private BigDecimal getCartItemAmount(List<OmsCartItem> itemList, List<PromotionProduct> promotionProductList) {
        BigDecimal amount = new BigDecimal(0);
        for (OmsCartItem item : itemList) {
            //计算出商品原价
            PromotionProduct promotionProduct = getPromotionProductById(item.getProductId(), promotionProductList);
            PmsSkuStock skuStock = null;
            if (promotionProduct != null) {
                skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
            } else {
                throw new ApiException("没有该商品的促销信息");
            }
            if (skuStock != null) {
                amount = amount.add(skuStock.getPrice().multiply(new BigDecimal(item.getQuantity())));
            } else {
                throw new ApiException("商品原价为空");
            }
        }
        return amount;
    }

    /**
     * 满减优惠
     *
     * @param totalAmount
     * @param fullReductionList
     * @return
     */
    private PmsProductFullReduction getProductFullReduction(BigDecimal totalAmount, List<PmsProductFullReduction> fullReductionList) {
        //按条件从高到低排序
        fullReductionList.sort((o1, o2) -> o2.getFullPrice().subtract(o1.getFullPrice()).intValue());
        for (PmsProductFullReduction fullReduction : fullReductionList) {
            if (totalAmount.subtract(fullReduction.getFullPrice()).intValue() >= 0) {
                return fullReduction;
            }
        }
        return null;
    }

    /**
     * 没有满足优惠条件的商品进行处理
     *
     * @param cartPromotionItemList
     * @param itemList
     * @param promotionProduct
     */
    private void handleNoReduce(List<CartPromotionItem> cartPromotionItemList, List<OmsCartItem> itemList, PromotionProduct promotionProduct) {
        for (OmsCartItem item : itemList) {
            CartPromotionItem cartPromotionItem = new CartPromotionItem();
            BeanUtils.copyProperties(item, cartPromotionItem);
            cartPromotionItem.setPromotionMessage("无优惠");
            cartPromotionItem.setReduceAmount(new BigDecimal(0));
            PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
            if (skuStock != null) {
                cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
            }
            cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
            cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
            cartPromotionItemList.add(cartPromotionItem);
        }
    }

    /**
     * 获取阶梯价格
     *
     * @param count
     * @param productLadderList
     * @return
     */
    private PmsProductLadder getProductLadder(int count, List<PmsProductLadder> productLadderList) {
        // 数量从小到大排序
        productLadderList.sort((o1, o2) -> o2.getCount() - o1.getCount());
        for (PmsProductLadder ladder : productLadderList) {
            if (count >= ladder.getCount()) {
                // 找到最小的满足满减的
                return ladder;
            }
        }
        return null;
    }

    /**
     * 获取打折优惠的促销信息
     *
     * @param ladder
     * @return
     */
    private String getLadderPromotionMessage(PmsProductLadder ladder) {
        return "打折优惠：" +
                "满" +
                ladder.getCount() +
                "件，" +
                "打" +
                ladder.getDiscount().multiply(new BigDecimal(10)) +
                "折";
    }

    /**
     * 获取购物车中指定商品的数量
     *
     * @param itemList
     * @return
     */
    private int getCartItemCount(List<OmsCartItem> itemList) {
        int count = 0;
        for (OmsCartItem item : itemList) {
            count += item.getQuantity();
        }
        return count;
    }

    /**
     * 获取商品原价
     *
     * @param promotionProduct
     * @param productSkuId
     * @return
     */
    private PmsSkuStock getOriginalPrice(PromotionProduct promotionProduct, Long productSkuId) {
        for (PmsSkuStock skuStock : promotionProduct.getSkuStockList()) {
            if (productSkuId.equals(skuStock.getId())) {
                return skuStock;
            }
        }
        return null;
    }

    /**
     * 根据ID获取商品的促销信息
     *
     * @param productId
     * @param promotionProductList
     * @return
     */
    private PromotionProduct getPromotionProductById(Long productId, List<PromotionProduct> promotionProductList) {
        for (PromotionProduct promotionProduct : promotionProductList) {
            if (productId.equals(promotionProduct.getId())) {
                return promotionProduct;
            }
        }
        return null;
    }

    /**
     * 查询商品的优惠信息
     *
     * @param cartItemList
     * @return
     */
    private List<PromotionProduct> getPromotionProductList(List<OmsCartItem> cartItemList) {
        List<Long> productIdList = new ArrayList<>();
        for (OmsCartItem cartItem : cartItemList) {
            productIdList.add(cartItem.getProductId());
        }
        return productDao.getPromotionProductList(productIdList);
    }

    /**
     * 以spu为单位对购物车中的商品进行分组
     *
     * @param cartItemList
     * @return
     */
    private Map<Long, List<OmsCartItem>> groupCartItemBySpu(List<OmsCartItem> cartItemList) {
        Map<Long, List<OmsCartItem>> productCartMap = new TreeMap<>();
        for (OmsCartItem cartItem : cartItemList) {
            List<OmsCartItem> productCartItemList = productCartMap.get(cartItem.getProductId());
            if (productCartItemList == null) {
                productCartItemList = new ArrayList<>();
                productCartItemList.add(cartItem);
                productCartMap.put(cartItem.getProductId(), productCartItemList);
            } else {
                productCartItemList.add(cartItem);
            }
        }
        return productCartMap;
    }

}
